package com.xcexample.electronicclasscard.login

import android.app.ActionBar.LayoutParams
import android.os.Bundle
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import com.google.gson.GsonBuilder
import com.tencent.mmkv.MMKV
import com.xcexample.electronicclasscard.log.LogUtils
import com.xcexample.electronicclasscard.databinding.LayoutLoginBinding
import com.xcexample.electronicclasscard.net.ApiFactory
import com.xcexample.electronicclasscard.net.BaseURL
import okhttp3.ResponseBody
import org.json.JSONException
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class LoginFragment(var token: (data: String) -> Unit) : DialogFragment() {

    private var _binding: LayoutLoginBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = LayoutLoginBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.dialog?.setCanceledOnTouchOutside(false)
        _binding?.tvLogin?.setOnClickListener {
            //admin xckj@2019
            //17637502443 123456
            var account = binding.etAccount.text.toString().trim()
            var pass = binding.etPass.text.toString().trim()
            if (TextUtils.isEmpty(account)) {
                Toast.makeText(this.context, "请输入账号", Toast.LENGTH_SHORT).show()

                return@setOnClickListener
            }
            if (TextUtils.isEmpty(pass)) {
                Toast.makeText(this.context, "请输入密码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            var retrofit = ApiFactory.create(BaseURL, false)
            var call = retrofit.loginByPwd(account, pass, "")
            call!!.enqueue(object : Callback<ResponseBody?> {
                override fun onResponse(
                    call: Call<ResponseBody?>,
                    response: Response<ResponseBody?>
                ) {
                    val json = response.body()?.string()
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, LoginResponse::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.code == 0) {
                            var fromJson =
                                gson.fromJson(obj?.data.toString(), LoginResponseData::class.java)
                            val defaultMMKV = MMKV.defaultMMKV()
                            defaultMMKV.encode("token", "${fromJson?.access_token}")
                            defaultMMKV.encode("account", account)
                            defaultMMKV.encode("pass", pass)
                            token(fromJson?.access_token ?: "")
                            dismiss()
                        } else {
                            Toast.makeText(this@LoginFragment.context, obj.msg, Toast.LENGTH_SHORT)
                                .show()
                        }

                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }

                }

                override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

                }
            })


        }
        _binding?.tvCancel?.setOnClickListener {
            dismiss()
        }

    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onStart() {
        super.onStart()
        val displayMetrics = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getMetrics(displayMetrics)
        val width = displayMetrics.widthPixels * 0.3
        dialog?.window?.setLayout(width.toInt(), LayoutParams.WRAP_CONTENT)
    }
}